<template>
    <div>
        <BasicDialogVue :data="dialog" @close="onCloseDialog(formRef)">
            <template #content>
                <el-form :model="formData" label-width="100px" :rules="rules" ref="formRef">
                    <el-form-item label="角色名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入角色名称" style="width: 240px" />
                    </el-form-item>
                    <el-form-item label="角色描述">
                        <el-input v-model="formData.description" placeholder="请输入角色描述" />
                    </el-form-item>
                    <el-form-item label="菜单设置" prop="permissionIds">
                        <el-tree-v2
                            ref="treeRef"
                            node-key="id"
                            style="width: 100%"
                            :height="400"
                            :data="menuList"
                            show-checkbox
                            :props="defaultProps"
                            :expand-on-click-node="true"
                        />
                    </el-form-item>
                </el-form>

                <div class="btn">
                    <el-button @click="onCloseDialog(formRef)">取消</el-button>
                    <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
                </div>
            </template>
        </BasicDialogVue>
    </div>
</template>
<script setup lang="ts">
import { menuPersmission, menuPersmissionTree, roleCreate, roleUpdate } from '@/apis/company/role'
import BasicDialogVue from '@/components/baseDialog/Index.vue'
import { ElMessage, ElTree, FormInstance } from 'element-plus'
import { ref, reactive, watchEffect, onMounted, onActivated } from 'vue'
/**
 * 初始化tree对象
 */
const treeRef = ref<InstanceType<typeof ElTree>>()

const props = defineProps(['data'])
const emit = defineEmits(['close'])
const formRef = ref()
const dialog = reactive({
    visible: false,
    title: '新增角色',
    width: '800px',
    id: '',
    type: 'create'
})
let resubmit = false
const formData: { [name: string]: string | string[] } = reactive({
    name: '',
    id: '',
    description: '',
    permissionIds: []
})
const defaultProps = reactive({
    value: 'id',
    label: 'name',
    children: 'subPermissions'
})

const rules = reactive({
    name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
})

const menuList: any[] = reactive([])

watchEffect(() => {
    dialog.visible = props.data.visible
    if (props.data.type === 'edit') {
        dialog.title = '编辑角色'
        dialog.type = 'edit'
        dialog.id = props.data.id
        formData.name = props.data.name
        formData.description = props.data.description
        menuPersmission(props.data.id).then(res => {
            if (Number(res.data.code) === 200) {
                treeRef.value?.setCheckedKeys(res.data.result, false)
            }
        })
    } else if (props.data.type === 'create') {
        dialog.title = '新增角色'
        dialog.type = 'create'
        formData.name = ''
        formData.description = ''
        if (treeRef.value) {
            setTimeout(() => {
                treeRef.value?.setCheckedKeys([], false)
            }, 50)
        }
    }
})

// 获取菜单
onMounted(() => {
    getMenu()
})

//获取菜单
const getMenu = () => {
    menuPersmissionTree({ types: '0,1,2' }).then(res => {
        console.log('res', res)
        if (Number(res.data.code) === 200) {
            menuList.length = 0
            menuList.push(...res.data.result)
        }
    })
}

//监听关闭
const onCloseDialog = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    if (treeRef.value) {
        treeRef.value?.setCheckedKeys([], false)
    }
    emit('close')
}
//监听提交
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!', formData)
            if (resubmit) {
                return
            }
            resubmit = true
            const ids: string[] = [
                ...(treeRef.value?.getCheckedKeys() as string[]),
                ...(treeRef.value?.getHalfCheckedKeys() as string[])
            ]
            if (dialog.type === 'create') {
                roleCreate({
                    name: formData.name,
                    description: formData.description,
                    permissionIds: ids
                }).then(
                    res => {
                        resubmit = false
                        if (Number(res.data.code) === 200) {
                            onCloseDialog(formEl)
                            ElMessage.success('创建成功')
                        }
                    },
                    () => {
                        resubmit = false
                    }
                )
            } else {
                roleUpdate({
                    name: formData.name,
                    description: formData.description,
                    permissionIds: ids,
                    id: dialog.id
                }).then(
                    res => {
                        resubmit = false
                        if (Number(res.data.code) === 200) {
                            onCloseDialog(formEl)
                            ElMessage.success('修改成功')
                        }
                    },
                    () => {
                        resubmit = false
                    }
                )
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
</script>
<style scoped lang="scss">
.btn {
    display: flex;
    justify-content: center;
    margin: 40px 0 16px 0;
}
</style>
